var params = new Object();
var tableNames;
var fileId;
var titleIndex;
var sheetName;
var sheetIndex;
var attachmentParamterId;
//是否为空
var isNullStatus = new Array("否", "是");
var columns = [];
var columnsRelate = new Object();

$(function () {
    //获取父页面的值
    setValue()

    var titleTt = $("#titleTt");
    initGrid2(titleTt);

});

//获取父页面的值
function setValue() {

    var name, value;
    var str = decodeURI(decodeURI(window.location.href));
    var num = str.indexOf("?")
    str = str.substr(num + 1); //取得所有参数   stringvar.substr(start [, length ]
    // 设值
    var arr = str.split("&"); //各个参数放到数组里
    for (var i = 0; i < arr.length; i++) {
        num = arr[i].indexOf("=");
        if (num > 0) {
            name = arr[i].substring(0, num);
            value = arr[i].substr(num + 1);
            if ("tableNames" == name) {
                tableNames = value;
            }
            if ("fileId" == name) {
                fileId = value;
            }
            if ("titleIndex" == name) {
                titleIndex = value;
            }
            if ("sheetName" == name) {
                sheetName = value;
            }
            if ("sheetIndex" == name) {
                sheetIndex = value;
            }
            if ("attachmentParamterId" == name) {
                attachmentParamterId = value;
            }
        }
    }
}

/**
 * 确定
 */
function btn_import() {

    var isSaveRelate = $("#isSaveRelate")[0].checked ? "1" : "0";
    params.sheetIndex = sheetIndex;
    params.sheetName = sheetName;
    params.titleIndex = titleIndex;
    params.isSaveRelate = isSaveRelate;
    params.fileId = fileId;
    params.tableNames = tableNames;
    //对应关系

    if (columns.length == 0) {
        $.alert("default", "info", "请先设置模板");
        return false;
    }
    var columnsList = JSON.stringify(columns);
    for (var i = 0; i < columnsList.length; i++) {
        columnsList = columnsList.replace("\"", "");
    }
    console.log(columnsList);
    params.columnsList = columnsList;
    params.attachmentParamterId =attachmentParamterId;
    if (isSaveRelate == "1") {
        var templateName = $("#templateName").val();
        if (templateName == "") {
            return $.alert("default", "info", "新模板名称不能为空");
        } else {
            params.templateName = templateName;
        }
    }

    setAjaxLoading();

    $.messager.alert("问题", "请确认是否要另存为新模板（勾选保存）及导入Excel表中数据？","confirm", function () {

            $.ajaxFileUpload({
                url: '/common/excelHandleIndex/importExcelAndSaveRelate',
                secureuri: false,
                fileElementId: 'file',
                type: "POST",
                data: params,
                dataType: "json",
                success: function (data) {
                    closeLayer();
                },
                error: function (data) {
                    var responseText = data.responseText;
                    var result = $.parseJSON(responseText.replace(/<.*?>/ig, ""));
                    var analyMsg = result;
                    if (analyMsg.code != '0000') {
                        $.messager.alert("操作提示", analyMsg.msg, "error", function () {
                        });
                    } else {
                        $.messager.alert("操作提示", analyMsg.msg, "info", function () {
                        });
                    }
                }
            });
            $("#loading").hide();

    });
}

/**
 * 取消
 */
function btnReset() {
    $("#file").val("");
    closeLayer();
}

// 初始化表格和数据
function initGrid2(titleTt) {
    var url = null;
    var columnsTitle = [
        {
            field: "columnNameShow",
            title: "表单字段名",
            align: "center",
            halign: "center",
            sortable: false,
            resizable: true,
            width: 80
        }, {
            field: "columnNames",
            title: "字段名称",
            hidden: true,
            align: "center",
            halign: "center",
            sortable: false,
            resizable: true,
            width: 80
        }, {
            field: "columnNameTypeShow",
            title: "数据类型",
            align: "center",
            halign: "center",
            sortable: false,
            resizable: true,
            width: 80
        }, {
            field: "columnNameType",
            title: "字段类型",
            align: "center",
            hidden: true,
            halign: "center",
            sortable: false,
            resizable: true,
            width: 80
        }, {
            field: "isnull",
            title: "是否为空",
            align: "center",
            halign: "center",
            sortable: false,
            resizable: true,
            hidden: false,
            width: 80,
            formatter: function (value, row, index) {
                return isNullStatus[value];
            }

        }, {
            field: "primaryKeyMark",
            title: "主键标识",
            align: "center",
            halign: "center",
            sortable: false,
            resizable: true,
            hidden: true,
            width: 80
        }, {
            field: "excelTitleName",
            title: "EXCEL标题",
            align: "center",
            halign: "center",
            sortable: false,
            resizable: true,
            hidden: false,
            width: 80
        }, {
            field: "formatConversion",
            title: "格式转换",
            align: "center",
            halign: "center",
            sortable: false,
            resizable: true,
            hidden: false,
            width: 80
        }, {
            field: "columnHiddenMark",
            title: "格式转换",
            align: "center",
            halign: "center",
            sortable: false,
            resizable: true,
            hidden: true,
            width: 10
        }



    ];
    initGridWithCheckSingleSelect(titleTt, columnsTitle, "");

    readExcelRelate();
}

$(document).ready(function () {

    $("#excelTitleComb").combobox({
        onSelect: function change() {
            chcek();
        }
    });

    $("#excelRelateComb").combobox({
        onSelect: function getExcelRelateTemplate() {
            var templateName = $('#excelRelateComb').combobox('getText');
            $.messager.alert("提示", "是否要使用已保存对应关系？","confirm", function () {

                    params.isReadRelate = "1";
                    params.templateName = templateName;
                    readExcelRelate();

            });
        }
    });

    $('#titleTt').datagrid({
        rowStyler: function (index, row) {
            if (row.columnHiddenMark == '1') {//条件
                return 'display:none';
            }
        }
    });
});

//点击下拉框时间
function chcek() {
    var f = true;
    var col;
    var excel;
    var isHave = true;
    var row = $("#titleTt").datagrid('getSelected');
    if(columns.length == 0){
        isHave =false
    }else {
        for (var i = 0; i < columns.length; i++) {
            if (row.primaryKeyMark == "1") {
                return $.alert("default", "info", "该列不允许配置");
            }
            if (row.columnNameShow == columns[i].dbColumnName) {
                //存在，
                isHave = true;
                f = false;
                break;
            } else {
                isHave = false;
                col = row.columnNameShow;
                f = true;
            }
        }
    }


    //DB和Excel不对应，添加
    if (!isHave) {
        var excelTitleComb = $('#excelTitleComb').combobox('getText');
        if (excelTitleComb == "" || excelTitleComb == null) {
            return $.alert("default", "info", "Excel标题不能为空");
        }
    } else {
        isHave = true;
        return $.alert("default", "info", "该行已设置对应关系");
    }
    if (f) {
        setDbTitle();
    }
}

//重置设置关系
function btnResetRelate() {
    var allRows = $('#titleTt').datagrid("getRows"); // 这段代码是// 对某个单元格赋值
    for (var i = 0; i < allRows.length; i++) {
        allRows[i].excelTitleName ="";
        columns.splice(0, columns.length);
        // 刷新该行, 只有刷新了才有效果
        $('#titleTt').datagrid('refreshRow', i);
    }

}

function readExcelRelate() {

    params.titleIndex = titleIndex;
    params.sheetName = sheetName;
    params.sheetIndex = sheetIndex;
    params.fileId = fileId;
    params.tableNames = tableNames;

    $.ajaxFileUpload({
        url: '/common/excelHandleIndex/getExcelTitle',
        secureuri: false,
        fileElementId: 'file',
        data: params,
        dataType: 'json',
        success: function (data) {
            closeLayer();
        },
        error: function (data) {
            var responseText = data.responseText;
            var result = $.parseJSON(responseText.replace(/<.*?>/ig, ""));
            var analyMsg = result;
            if (analyMsg.code != '0000') {
                $.messager.alert("操作提示", analyMsg.msg, "error", function () {
                });
                setTimeout("closeLayer()", 1000);
            } else {
                // Load数据 Excel标题
                if (analyMsg.returnObject.titlelist.length > 0) {

                    var taxpayer = analyMsg.returnObject.titlelist;
                    $("#excelTitleComb").combobox({
                        'valueField': 'excelTitleId',
                        'textField': 'excelTitle',
                        'data': taxpayer
                    });

                }

                //  Load数据 已保存的个人模板
                if (analyMsg.returnObject.excelHandleRelateDtoList.length > 0) {
                    var rows = analyMsg.returnObject.excelHandleRelateDtoList;
                    //清空原对应关系
                    setRelate(rows);
                } else {
                    //清空原对应关系
                    var rows = [];
                    setRelate(rows);
                }

                // 加载关系
                if (analyMsg.returnObject.haveRelateDtoList.length > 0) {
                    var rows = analyMsg.returnObject.haveRelateDtoList;
                    if (columns.length == 0) {
                        setHaveRelateDtoList(rows);
                    } else {
                        //清空原对应关系
                        columns.splice(0, columns.length);
                        setHaveRelateDtoList(rows);
                    }
                } else {
                    //清空原对应关系
                    columns.splice(0, columns.length);
                    var rows = [];
                    setHaveRelateDtoList(rows);
                }

                //加载后台配置模板信息
                var titleTt = $("#titleTt");
                if (analyMsg.returnObject.excelHandleDtoList.length > 0) {
                    //清空原始数据
                    titleTt.datagrid('loadData', {total: 0, rows: []});
                    titleTt.datagrid("loadData", analyMsg.returnObject.excelHandleDtoList);
                    displayMsg(titleTt);
                } else {
                    titleTt.datagrid('loadData', {
                        total: 0,
                        rows: []
                    });
                }
            }
        }
    });
}

function setRelate(rows) {
    var taxpayer = rows;
    $("#excelRelateComb").combobox({
        'valueField': 'templateName',
        'textField': 'templateName',
        'data': taxpayer
    });
}

function setHaveRelateDtoList(rows) {
    for (var i = 0; i < rows.length; i++) {
        var columnsRelate = new Object();
        var row = rows[i];
        var dbColumnName = row.columnNameShow;
        var excelTitleName = row.excelTitleName;
        columnsRelate.showRelateName = '表字段：' + dbColumnName + '-Excel标题：' + excelTitleName;
        columnsRelate.excelTitleName = excelTitleName;
        columnsRelate.dbColumnName = dbColumnName;
        columns.push(columnsRelate);
    }
}


//设置已选对应关系
function setDbTitle() {

    var rows = $('#titleTt').datagrid('getSelections');
    if (rows.length == 0) {
        $.alert("default", "info", "请选择Excel工作簿");
        return false;
    }

    var excelTitleComb = $('#excelTitleComb').combobox('getText');
    if (excelTitleComb == "" || excelTitleComb == null) {
        return $.alert("default", "info", "Excel标题不能为空");
    }
    var row = rows[0];
    row.excelTitleName= excelTitleComb;

    var allrows = $('#titleTt').datagrid('getRows');
    for(var i = 0 ; i< allrows.length;i++){
        if(row.id ==allrows[i].id){
            // 刷新该行, 只有刷新了才有效果
            $('#titleTt').datagrid('refreshRow', i);
            break;
        }
    }

    //设置关系
    var columnsRelate = new Object();
    var dbColumnName = row.columnNameShow;
    var excelTitleName = row.excelTitleName;
    columnsRelate.showRelateName = '表字段：' + dbColumnName + '-Excel标题：' + excelTitleName;
    columnsRelate.excelTitleName = excelTitleName;
    columnsRelate.dbColumnName = dbColumnName;
    columns.push(columnsRelate);
}